package cn.swust.service.serviceimpl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import cn.swust.model.SetContentBean;
import cn.swust.service.SetContentService;
import cn.swust.util.DBUtil;

public class SetContentServiceImpl implements SetContentService {

	public int addSetContent(SetContentBean setting) {
		int ret = 0;
		try{
		String insertSql = "insert into setcontent(set_type,set_content,set_picpath,set_picurl)" +
		" values (" + setting.getType() + ",'" + setting.getContent() + "','" +
		setting.getPicPath() + "','" + setting.getPicUrl() + "')";
		Connection conn = DBUtil.getConnection();
		Statement state = conn.createStatement();
		state.execute(insertSql, Statement.RETURN_GENERATED_KEYS);
		ResultSet rs = state.getGeneratedKeys();
		while(rs.next())
			ret = rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return ret;
	}

	public int delSetContent(int id) {
		String delSql = "delete from setcontent where set_id = " + id;
		return DBUtil.updateSql(delSql);
	}

	public int modSetContent(int id, SetContentBean setting) {
		String modSql = "update setcontent set set_type = "  + setting.getType() + ",set_content = '" +
		setting.getContent() + "',set_picpath = '" + setting.getPicPath() + "',set_picurl = '" +
		setting.getPicUrl() + "' where set_id = " + id;
		return DBUtil.updateSql(modSql);
	}

	public SetContentBean queryById(int id) {
		String querySql = "select * from setcontent where set_id = " + id;
		ResultSet rs = DBUtil.querySql(querySql, DBUtil.creatStatement(DBUtil.getConnection()));
		SetContentBean set = new SetContentBean();
		try {
			if (rs.next()) {
				set.setId(rs.getInt("set_id"));
				set.setContent(rs.getString("set_content"));
				set.setPicPath(rs.getString("set_picpath"));
				set.setPicUrl(rs.getString("set_picurl"));
				set.setType(rs.getInt("set_type"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return set;
	}

	public ArrayList<SetContentBean> queryByType(int type) {
		String querySql = "select * from setcontent where set_type = " + type;
		ResultSet rs = DBUtil.querySql(querySql, DBUtil.creatStatement(DBUtil.getConnection()));
		ArrayList<SetContentBean> setList = new ArrayList<SetContentBean>();
		try {
			while (rs.next()) {
				SetContentBean set = new SetContentBean();
				set.setId(rs.getInt("set_id"));
				set.setContent(rs.getString("set_content"));
				set.setPicPath(rs.getString("set_picpath"));
				set.setPicUrl(rs.getString("set_picurl"));
				set.setType(rs.getInt("set_type"));
				setList.add(set);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return setList;
	}

}
